import PlayerManager from "../manager/PlayerManager";
import Player from "../player/Player";
import UiPointer from "./UiPointer";

const { ccclass, property } = cc._decorator;
const cameraClamp = [cc.v3(-2455, -2785), cc.v3(2455, 2785)]

@ccclass
export default class CameraFollow extends cc.Component {

    contorlPlayer: Player = null;
    target: cc.Vec3;
    lastDt: number = 0.01;

    start() {
        this.contorlPlayer = PlayerManager.instance.controllerPlayer;
        this.target = this.contorlPlayer.node.position;
        this.scheduleOnce(() => {
            this.node.position = this.target;
        })
        this.contorlPlayer.node.on(cc.Node.EventType.POSITION_CHANGED, this.updatePlayerTarget, this);

        PlayerManager.instance.controllerPlayer.node.on(Player.EventType.安家, this.onMakeHome, this);
    }

    //相机跟随角色
    updatePlayerTarget() {
        this.target = this.contorlPlayer.node.position;
    }

    onMakeHome() {
        this.contorlPlayer.node.targetOff(this);
        //跟随指针
        UiPointer.instance.node.on(cc.Node.EventType.POSITION_CHANGED, () => {
            this.target = UiPointer.instance.node.position;
        }, this);
    }

    update(dt) {
        let sub = this.target.sub(this.node.position);
        let dir = sub.normalize();
        let distance = sub.mag();
        let moveSpeed = cc.v2(1000, 0).lerp(cc.v2(4000, 0), distance / 800).x;
        //相机跟随目标
        let position: cc.Vec3;
        if (distance < this.lastDt * moveSpeed + 5) {
            position = this.node.position = this.target;
        } else {
            position = this.node.position = this.node.position.add(dir.mul(moveSpeed * dt));
        }
        position = position.clampf(cameraClamp[0], cameraClamp[1]);
        this.node.position = position;
        this.lastDt = dt;
    }

    protected onDestroy(): void {
        UiPointer.instance.node.targetOff(this);
    }
}
